import React, { useEffect, useCallback } from 'react';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import ArrowBackIosNewIcon from '@mui/icons-material/ArrowBackIosNew';
import ArrowForwardIosIcon from '@mui/icons-material/ArrowForwardIos';
import Box from '@mui/material/Box';
import Button from '@mui/material/Button';

/**
 * 通用图片预览弹窗组件
 * @param {boolean} open 是否打开
 * @param {function} onClose 关闭回调
 * @param {Array} images 图片数组（每项至少包含src、alt、originalName、filename等）
 * @param {number} currentIndex 当前图片索引
 * @param {function} onIndexChange 切换图片时回调
 */
export default function ImagePreviewDialog({ open, onClose, images = [], currentIndex = 0, onIndexChange }) {
  // Hooks 必须在组件顶层调用
  const handleKeyDown = useCallback((e) => {
    if (!open) return;
    if (e.key === 'ArrowLeft' && currentIndex > 0) {
      onIndexChange && onIndexChange(currentIndex - 1);
    } else if (e.key === 'ArrowRight' && currentIndex < images.length - 1) {
      onIndexChange && onIndexChange(currentIndex + 1);
    } else if (e.key === 'Escape') {
      onClose && onClose();
    }
  }, [open, currentIndex, images.length, onIndexChange, onClose]);

  useEffect(() => {
    if (open) {
      window.addEventListener('keydown', handleKeyDown);
      return () => window.removeEventListener('keydown', handleKeyDown);
    }
  }, [open, handleKeyDown]);

  if (!images || images.length === 0) return null;
  const image = images[currentIndex] || images[0];

  // 查看原图URL推断
  const getOriginalUrl = (img) => {
    // 优先使用originalUrl/原图字段，否则尝试用filename
    if (img.originalUrl) return img.originalUrl;
    if (img.filename && img.datePath) {
      // 兼容API_URL变量
      const API_URL = process.env.REACT_APP_API_URL || 'http://localhost:5000';
      return `${API_URL}/uploads/${img.datePath}/${img.filename}`;
    }
    return img.src || img.url || img.path;
  };

  const handlePrev = (e) => {
    e.stopPropagation();
    if (currentIndex > 0 && onIndexChange) onIndexChange(currentIndex - 1);
  };
  const handleNext = (e) => {
    e.stopPropagation();
    if (currentIndex < images.length - 1 && onIndexChange) onIndexChange(currentIndex + 1);
  };
  const handleViewOriginal = () => {
    const url = getOriginalUrl(image);
    if (url) window.open(url, '_blank');
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle sx={{ pr: 6 }}>
        {image.originalName || image.alt || '图片预览'}
        <IconButton
          aria-label="close"
          onClick={onClose}
          sx={{ position: 'absolute', right: 8, top: 8, color: 'grey.500' }}
        >
          <CloseIcon />
        </IconButton>
      </DialogTitle>
      <DialogContent sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: { xs: 180, sm: 300 }, position: 'relative', p: { xs: 1, sm: 2 } }}>
        <IconButton
          onClick={handlePrev}
          disabled={currentIndex === 0}
          sx={{ position: 'absolute', left: 8, top: '50%', transform: 'translateY(-50%)', bgcolor: 'rgba(255,255,255,0.7)', display: { xs: 'none', sm: 'flex' } }}
        >
          <ArrowBackIosNewIcon />
        </IconButton>
        <Box sx={{ maxWidth: { xs: '96vw', sm: '80vw' }, maxHeight: { xs: '50vh', sm: '60vh' }, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <img
            src={image.src || image.url || image.path}
            alt={image.originalName || image.alt || ''}
            style={{ maxWidth: '100%', maxHeight: '60vh', borderRadius: 8 }}
          />
        </Box>
        <IconButton
          onClick={handleNext}
          disabled={currentIndex === images.length - 1}
          sx={{ position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)', bgcolor: 'rgba(255,255,255,0.7)', display: { xs: 'none', sm: 'flex' } }}
        >
          <ArrowForwardIosIcon />
        </IconButton>
      </DialogContent>
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', pb: 2 }}>
        <Button
          variant="contained"
          onClick={handleViewOriginal}
          sx={{
            borderRadius: 2,
            px: 3,
            fontSize: { xs: '0.95rem', sm: '1rem' },
            fontWeight: 600,
            textTransform: 'none',
            background: 'linear-gradient(45deg, #2196F3 30%, #21CBF3 90%)',
            boxShadow: '0 4px 20px rgba(33, 150, 243, 0.2)',
            '&:hover': {
              background: 'linear-gradient(45deg, #1976D2 30%, #1E88E5 90%)',
              boxShadow: '0 6px 25px rgba(33, 150, 243, 0.3)',
              transform: 'translateY(-1px)',
            },
            '&:active': {
              transform: 'translateY(1px)',
            },
            transition: 'all 0.3s ease',
          }}
        >
          查看原图
        </Button>
      </Box>
    </Dialog>
  );
} 